package com.athuiju.fenxiaoback.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.athuiju.fenxiaoback.entity.UcenterMember;
import com.athuiju.fenxiaoback.entity.vo.CurrentUser;
import com.athuiju.fenxiaoback.utils.JwtUtils;
import com.athuiju.fenxiaoback.utils.anno.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class LoginUserInterceptor implements HandlerInterceptor {
    public static final String USER_KEY = "USER_ID";
    public static final String USER_INFO = "USER_INFO";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Token annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Token.class);
        }else{
            return true;
        }
        //没有声明需要权限,或者声明不验证权限
        if(annotation == null || annotation.validate() == false){
            return true;
        }
//从header中获取token
        String token = request.getHeader("token");
        if(token == null){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null ;
            JSONObject res = new JSONObject();
            res.put("code",20005);
            res.put("message","缺少token拒绝访问");
            out = response.getWriter();
            out.append(res.toString());
            return false;
        }


        boolean b = JwtUtils.checkToken(request);

        if (!b){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null ;
            JSONObject res = new JSONObject();
            res.put("code",20005);
            res.put("message","请登录...");
            out = response.getWriter();
            out.append(res.toString());
            return false;
        }
        String memberId = JwtUtils.getMemberIdByJwtToken(request);

        request.setAttribute(USER_KEY, memberId);
        CurrentUser user=new CurrentUser();
        user.setId(Long.parseLong( memberId));

        request.setAttribute(USER_INFO, user);

        return true;
    }
}
